<template>
  <Layout title="缴费详情" :has-back="true" :has-tabbar="false" ref="layout">
    <view
      style="
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        padding: 20rpx;
        display: flex;
        flex-direction: column;
      "
    >
      <view>
        <view style="display: flex; column-gap: 20rpx">
          <view style="flex: 1; min-width: 0">
            <u-button type="info" @click="datetimeSelect"
              ><text style="font-size: 40rpx"
                >日期选择: {{ dateRange }}</text
              ></u-button
            >
          </view>
          <view>
            <u-button type="error" @click="ignoreDatetime">
              <text style="font-size: 40rpx">忽略日期</text>
            </u-button>
          </view>
        </view>
        <u-calendar
          :show="calendar.show"
          mode="range"
          @confirm="calendarConfirm"
          @close="calendarClose"
          :show-confirm="true"
          :maxDate="maxDate"
          :minDate="minDate"
          :defaultDate="defaultDate"
          :monthNum="13"
          :allowSameDay="true"
        ></u-calendar>
      </view>
      <view style="margin-top: 20rpx">
        <u-button type="primary" @click="searchRefresh">
          <text style="font-size: 40rpx">筛选</text>
        </u-button>
      </view>
      <view
        style="flex: 1; min-height: 0; margin-top: 20rpx; margin-bottom: 20rpx"
      >
        <z-paging ref="paging" v-model="payList" @query="search" :fixed="false">
          <view style="display: flex; flex-direction: column; row-gap: 20rpx">
            <view v-for="pay of payList" :key="pay.uuid">
              <view
                style="
                  border: 2rpx solid gray;
                  display: flex;
                  flex-direction: row;
                  flex-wrap: wrap;
                  column-gap: 20rpx;
                "
              >
                <view v-for="url of pay.attachment" :key="url">
                  <u-image
                    :src="url"
                    width="100rpx"
                    height="100rpx"
                    @click="imageClick(url)"
                  ></u-image>
                </view>
              </view>
            </view>
          </view>
        </z-paging>
      </view>
      <u-button type="warning" @click="selectImage">
        <text style="font-size: 40rpx">上传缴费图片</text>
      </u-button>
    </view>
  </Layout>
</template>
<script>
import Layout from "@/pages/component/layout/index.vue";
import { getPayByPagination, createPay } from "@/api/pay";
import { getCurrentDatetime } from "@/api/datetime";
import dayjs from "dayjs";
import { showErrorToast, showCreateOkToast } from "@/util/message";
import { uploadFile } from "@/api/upload";

export default {
  components: { Layout },
  onLoad(event) {
    this.owner = JSON.parse(event.owner);
    this.formData.ownerUuid = this.owner.uuid;
    getCurrentDatetime()
      .then((currentDatetime) => {
        let nowDatetime = dayjs(currentDatetime.data.datetime);
        this.minDate = nowDatetime.subtract(1, "year").format("YYYY-MM-DD");
        this.maxDate = nowDatetime.format("YYYY-MM-DD");
        this.defaultDate = nowDatetime.format("YYYY-MM-DD");
        this.formData.sendDateRange = [nowDatetime.format("YYYY-MM-DD")];
      })
      .catch((error) => {
        showErrorToast(error);
      });
  },
  computed: {
    dateRange() {
      if (this.formData.sendDateRange.length === 0) {
        return "";
      } else if (this.formData.sendDateRange.length === 1) {
        return this.formData.sendDateRange[0];
      } else {
        return `${this.formData.sendDateRange[0]} 至 ${this.formData.sendDateRange[1]}`;
      }
    },
  },
  data() {
    return {
      payList: [],
      formData: {
        sendDateRange: [],
        ownerUuid: "",
      },
      owner: {},
      calendar: {
        show: false,
      },
      maxDate: "",
      minDate: "",
      defaultDate: "",
    };
  },
  methods: {
    imageClick(url) {
      uni.previewImage({
        urls: [url],
      });
    },
    async selectImage() {
      try {
        let imageInfo = await uni.chooseImage({
          count: 6,
          sourceType: ["album"],
        });
        let { tempFilePaths } = imageInfo;
        let urlPromiseList = [];
        for (let i = 0; i < tempFilePaths.length; i++) {
          urlPromiseList.push(uploadFile({ filePath: tempFilePaths[i] }));
        }
        let result = await Promise.all(urlPromiseList);
        let attachment = result.map((item) => {
          return item.data.url;
        });
        attachment = JSON.stringify(attachment);
        let ownerUuid = this.owner.uuid;
        await createPay({ attachment, ownerUuid });
        showCreateOkToast();
        this.searchRefresh();
      } catch (error) {
        if (error.message) {
          showErrorToast(error);
        }
      }
    },
    ignoreDatetime() {
      this.formData.sendDateRange = [];
    },
    calendarClose() {
      this.calendar.show = false;
    },
    datetimeSelect() {
      this.calendar.show = true;
    },
    calendarConfirm(event) {
      if (event[0] === event[1]) {
        this.formData.sendDateRange = [event[0]];
      } else {
        this.formData.sendDateRange = [event[0], event[event.length - 1]];
      }
      this.calendarClose();
    },
    async searchRefresh() {
      this.$refs.paging.refresh();
    },
    async search(currentPage, pageSize) {
      let result = await getPayByPagination({
        currentPage,
        pageSize,
        ...this.formData,
      });
      let list = result.data.list;
      list = list.map((item) => {
        return {
          ...item,
          attachment: JSON.parse(item.attachment),
        };
      });
      this.$refs.paging.complete(list);
    },
  },
};
</script>
